#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string>
#include <strings.h>
#include <cstring>

void Usage(char *argv[])
{
    printf("%s\n\t[IP] [Port]", argv[0]);
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv);
        exit(1);
    }

    uint16_t port = htons(std::stoi(argv[2]));
    uint32_t ip = inet_addr(argv[1]);

    // 创建套接字
    int sockFd = socket(AF_INET, SOCK_DGRAM, 0);
    if (-1 == sockFd)
    {
        std::cerr << "socket() error, errno: " << errno << "errorstring: " << strerror(errno) << std::endl;
        exit(2);
    }

    //信息接收方(server)的socket信息
    struct sockaddr_in server_addr;
    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_addr.s_addr = ip;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = port;

    while (true)
    {
        std::string massage;
        std::cout << "client massage# ";
        std::getline(std::cin, massage);

        // 发送数据
        int ret = sendto(sockFd, massage.c_str(), massage.size(), 0, (struct sockaddr *)&server_addr, sizeof(server_addr));
        if (-1 == ret)
        {
            std::cerr << "sendto() error, errno: " << errno << "errorstring: " << strerror(errno) << std::endl;
            exit(3);
        }

        //用来记录信息发送方（不一定是server）的socket信息
        struct sockaddr_in all_addr;
        bzero(&all_addr, sizeof(all_addr));
        socklen_t all_addrLen = sizeof(all_addr);

        char buffer[1024] = {0};
        // 接收数据
        recvfrom(sockFd, buffer, sizeof(buffer), 0, (struct sockaddr*)&all_addr, &all_addrLen);
        std::cout << "client receve# " << buffer << std::endl;
    }
    return 0;
}